package com.itboye.ihomebank.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.FangYuanRenZhengAdpter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.me.ActivityEditHouse;
import com.itboye.ihomebank.photo.CopyOfPhotoActivity;
import com.itboye.ihomebank.photo.CopyOfTestPicActivity;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.uploadmultipleimage.MultipartRequest;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;

public class ActivityRenZheng extends BaseOtherActivity implements Observer {

	PopupWindows cameraPopupWindow;
	int type;
	GridView fangchanzheng, weituoshu, shoufanghetong;
	ImageView close_icon;
	private String picture_name;
	private String fileName02;
	private String localSelectPath02;
	private static final int REAL_PHONE = 101;
	private static final int REAL_PICTURE = 102;
	HousePresenter housePresenter;
	TextView card_tijiao, add_shap_title_tv;
	private String uid;
	private String houseNo;
	private File file02;
	String role;
	LinearLayout li_weituoshu;
	public static List<String> listImg = new ArrayList<>();// 房产证
	public static List<String> listImg2 = new ArrayList<>();// 委托书
	public static List<String> listImg3 = new ArrayList<>();// 住房合同
	private FangYuanRenZhengAdpter adapter1;
	private FangYuanRenZhengAdpter adapter2;
	private FangYuanRenZhengAdpter adapter3;
	EditText fabu_addressdetail, fabu_fangchanzhengno;
	private String no;
	private String addrDetail;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.open_camera:
			opencamera();
			break;
		case R.id.pick_image:
			pickImage();
			break;
		case R.id.card_tijiao:
			uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
			// String imgFangChanZheng = fangchanzheng.getTag() + "";
			// if (imgFangChanZheng.equals("")) {
			// ByAlert.alert("请选择房产证图片");
			// return;
			// }
			// String imgWeiTuoShu = weituoshu.getTag() + "";
			// if (role.equals("jingjiren")) {
			// if (imgFangChanZheng.equals("")) {
			// ByAlert.alert("请选择委托书图片");
			// return;
			// }
			// }
			no = fabu_fangchanzhengno.getText().toString();
			if (no.equals("")) {
				ByAlert.alert("请输入房产证编号");
				return;
			}
			addrDetail = fabu_addressdetail.getText().toString();
			if (addrDetail.equals("")) {
				ByAlert.alert("请输入详细地址");
				return;
			}
			showProgressDialog("图片上传中", false);

			fangchanzheng(listImg);
			// housePresenter.fangYuanRenZheng(uid, houseNo, pass, msg);
			break;
		case R.id.close_icon:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		listImg.clear();
		listImg2.clear();
		listImg3.clear();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		adapter1 = new FangYuanRenZhengAdpter(this, listImg);
		fangchanzheng.setAdapter(adapter1);
		adapter2 = new FangYuanRenZhengAdpter(this, listImg2);
		weituoshu.setAdapter(adapter2);
		adapter3 = new FangYuanRenZhengAdpter(this, listImg3);
		shoufanghetong.setAdapter(adapter3);
		// adapter1.notifyDataSetChanged();
		// adapter2.notifyDataSetChanged();
		// adapter3.notifyDataSetChanged();
	}

	private void shoufanghetong(List<String> path, String type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("uid", uid);
		params.put("type", type);
		params.put("house_no", houseNo);
		List<File> f = new ArrayList<File>();
		for (int i = 0; i < path.size(); i++) {
			f.add(new File(path.get(i)));
		}
		MultipartRequest multipartRequest = new MultipartRequest(
				NetPublicConstant.URL
						+ "/file/upload?client_id=by565fa4facdb191",
				new Listener<String>() {

					@Override
					public void onResponse(String arg0) {

//						ByAlert.alert("3---------" + arg0);
						housePresenter
								.verifyApply(uid, houseNo, no, addrDetail);
						// finish();
						// TODO Auto-generated method stub
						// if (role.equals("jingjiren")) {
						// weiTuoShu(weituoshu);
						// } else {
						// closeProgressDialog();
						// ByAlert.alert("请求已提交");
						// }
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}
				}, "image[]", f, params);
		MyApplcation.addRequest(multipartRequest);
	}

	private void fangchanzheng(List<String> imgFangChanZheng) {
		// TODO Auto-generated method stub
		Map<String, String> params = new HashMap<String, String>();
		params.put("uid", uid);
		params.put("type", "property");
		params.put("house_no", houseNo);
		List<File> f = new ArrayList<File>();
		for (int i = 0; i < imgFangChanZheng.size(); i++) {
			f.add(new File(imgFangChanZheng.get(i)));
		}
		// UploadImage.getInstance()
		// .execute(imgUri, "property", this, houseNo);// property 房产证
		// UploadImage.getInstance().execute(imgUri, "agent", this, houseNo);//
		// 委托书

		MultipartRequest multipartRequest = new MultipartRequest(
				NetPublicConstant.URL
						+ "/file/upload?client_id=by565fa4facdb191",
				new Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						// TODO Auto-generated method stub
						if (role.equals("jingjiren")) {
							weiTuoShu(listImg2);
						} else {
							housePresenter.verifyApply(uid, houseNo, no,
									addrDetail);
							// closeProgressDialog();
							// ByAlert.alert("请求已提交");
						}

					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}
				}, "image[]", f, params);
		MyApplcation.addRequest(multipartRequest);
	}

	protected void weiTuoShu(List<String> weituoshu) {
		// TODO Auto-generated method stub
		Map<String, String> params = new HashMap<String, String>();
		params.put("uid", uid);
		params.put("type", "agent");
		params.put("house_no", houseNo);
		List<File> f = new ArrayList<File>();
		for (int i = 0; i < weituoshu.size(); i++) {
			f.add(new File(weituoshu.get(i)));
		}

		// UploadImage.getInstance()
		// .execute(imgUri, "property", this, houseNo);// property 房产证
		// UploadImage.getInstance().execute(imgUri, "agent", this, houseNo);//
		// 委托书

		MultipartRequest multipartRequest = new MultipartRequest(
				NetPublicConstant.URL
						+ "/file/upload?client_id=by565fa4facdb191",
				new Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						// TODO Auto-generated method stub

						shoufanghetong(listImg3, "shoufang");
						// try {

						// closeProgressDialog();
						// } catch (Exception e) {
						// // TODO: handle exception
						// }
						// finish();
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}
				}, "image[]", f, params);

		MyApplcation.addRequest(multipartRequest);
	}

	void opencamera() {
		picture_name = android.text.format.DateFormat.format("yyyyMMdd_hhmmss",
				Calendar.getInstance(Locale.CHINA)) + ".jpg";
		file02 = new File("/sdcard/Image/");
		file02.mkdirs();// 创建文件夹
		fileName02 = "/sdcard/Image/" + picture_name;
		file02 = new File(fileName02);

		/**
		 * 打开照相机
		 */
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			final Intent intent = new Intent();
			final Intent intent_camera = getPackageManager()
					.getLaunchIntentForPackage("com.android.camera");
			if (intent_camera != null) {
				intent.setPackage("com.android.camera");
			}
			intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file02));// file是拍照保存文件
			startActivityForResult(intent, REAL_PHONE);// requestCode这个你懂的……
			// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// startActivityForResult(intent, REAL_PHONE);

		} else {
			Toast.makeText(ActivityRenZheng.this, "请确认已经插入SD卡", 2000).show();
		}

	}

	void pickImage() {
		Intent intent2 = new Intent();
		intent2.setType("image/*");// 可选择图片视频
		// 修改为以下两句代码
		intent2.setAction(Intent.ACTION_PICK);
		intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
		startActivityForResult(intent2, REAL_PICTURE);
	}

	void setImageCamera(Intent data) {

		String sdStatus01 = Environment.getExternalStorageState();
		if (!sdStatus01.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.i("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}

		// Bundle bundle02 = data.getExtras();
		// Bitmap bitmap02 = (Bitmap) bundle02.get("data");//
		// 获取相机返回的数据，并转换为Bitmap图片格式
		// SavePicInLocal(bitmap);
		FileOutputStream b02 = null;

		Bitmap bitmap02 = BitmapFactory.decodeFile(file02.getAbsolutePath());
		try {
			b02 = new FileOutputStream(fileName02);
			bitmap02.compress(Bitmap.CompressFormat.JPEG, 100, b02);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b02.flush();
				b02.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// Bitmap bit03 = BitmapFactory.decodeFile(fileName02);
		if (type == 1) {
			listImg.add(localSelectPath02);

			adapter1.notifyDataSetChanged();
			// fangchanzheng.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		} else if (type == 2) {
			listImg2.add(localSelectPath02);
			adapter2.notifyDataSetChanged();
			// weituoshu.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		} else if (type == 3) {
			listImg3.add(localSelectPath02);
			adapter3.notifyDataSetChanged();
			// weituoshu.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		}
		try {
			cameraPopupWindow.dismiss();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void setPickImg(Intent data) {
		/**
		 * 当选择的图片不为空的话，在获取到图片的途径
		 */
		Uri selectedImage04 = data.getData();
		localSelectPath02 = null;
		localSelectPath02 = getRealPathFromURI(selectedImage04);
		if (type == 1) {
			listImg.add(localSelectPath02);

			adapter1.notifyDataSetChanged();
			// fangchanzheng.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		} else if (type == 2) {
			listImg2.add(localSelectPath02);
			adapter2.notifyDataSetChanged();
			// weituoshu.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		} else if (type == 3) {
			listImg3.add(localSelectPath02);
			adapter3.notifyDataSetChanged();
			// weituoshu.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		}

		cameraPopupWindow.dismiss();
	}

	/**
	 * 该方法用于获取文件的真实路径从URI 从相机拍摄
	 */
	private String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REAL_PHONE:// 相机
				setImageCamera(data);
				break;
			case REAL_PICTURE:
				setPickImg(data);
				break;
			}
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_renzhengfangyuan;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		add_shap_title_tv.setText("房源认证");
		fangchanzheng.setTag("");
		weituoshu.setTag("");
		housePresenter = new HousePresenter(this);
		houseNo = getIntent().getStringExtra("house_no");
		role = getIntent().getStringExtra("role");
		if (role.equals("fangdong")) {
			li_weituoshu.setVisibility(View.GONE);
		} else if (role.equals("jingjiren")) {
			li_weituoshu.setVisibility(View.VISIBLE);
		}
		adapter1 = new FangYuanRenZhengAdpter(this, listImg);
		fangchanzheng.setAdapter(adapter1);
		adapter2 = new FangYuanRenZhengAdpter(this, listImg2);
		weituoshu.setAdapter(adapter2);
		adapter3 = new FangYuanRenZhengAdpter(this, listImg3);
		shoufanghetong.setAdapter(adapter3);
		fangchanzheng.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				type = 1;
				if (listImg.size() == arg2) {
					cameraPopupWindow = new PopupWindows(ActivityRenZheng.this,
							fangchanzheng);
				} else {
					Intent intent = new Intent(ActivityRenZheng.this,
							CopyOfPhotoActivity.class);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", 2);
					startActivityForResult(intent, 101);
				}
			}
		});
		weituoshu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				type = 2;
				if (listImg2.size() == arg2) {
					cameraPopupWindow = new PopupWindows(ActivityRenZheng.this,
							weituoshu);
				} else {
					Intent intent = new Intent(ActivityRenZheng.this,
							CopyOfPhotoActivity.class);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", 3);
					startActivityForResult(intent, 101);
				}
			}
		});
		shoufanghetong.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				type = 3;
				if (listImg3.size() == arg2) {
					cameraPopupWindow = new PopupWindows(ActivityRenZheng.this,
							shoufanghetong);
				} else {
					Intent intent = new Intent(ActivityRenZheng.this,
							CopyOfPhotoActivity.class);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", 4);
					startActivityForResult(intent, 101);
				}
			}
		});

	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					opencamera();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(ActivityRenZheng.this,
							CopyOfTestPicActivity.class);
					intent.putExtra("type", type);
					if (type == 1)
						intent.putExtra("max", 3 - listImg.size());
					else if (type == 2)
						intent.putExtra("max", 3 - listImg2.size());
					else if (type == 3)
						intent.putExtra("max", 3 - listImg3.size());
					startActivity(intent);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.verifyApply_success) {
				ByAlert.alert("请求已提交");
				finish();
			} else if (entity.getEventType() == HousePresenter.verifyApply_fail) {
				ByAlert.alert(entity.getData());
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
